﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Reflection;
using Pixysoft.Weblications.Sango.Protocol.player;
using Pixysoft.Weblications.Sango.Dao;
using Pixysoft.Weblications.Sango.Environment;
using Pixysoft.Weblications.Sango.Formular;
using Pixysoft.Weblications.Sango.Protocol;

namespace Pixysoft.Weblications.Sango.Command.section
{
    partial class SangoSectionHandler
    {
        public section_invest section_invest(long sectionserialcode, long value)
        {
            string userCode = SangoManager.Authentication();

            section_invest response = ReflectionManager.CreatePojo<section_invest>();
            response.Succeed = false;

            Entities.Usr_Profile profile = UsrProfileDao.getUsrProfile(userCode);

            Entities.Usr_Section section = UsrSectionDao.GetSection(userCode);

            Entities.Cti_Section citySection = CitySectionHelper.searchSectionByCode(sectionserialcode);
            if (citySection.Belongnationtypecode != section.Nationtypecode)
            {
                response.Message = "异国地区，无法投资";
                return response;
            }

            if (!UsrProfileDao.tryDecreaseCashvalue(profile, value))
            {
                response.Message = "银币余额不足";
                return response;
            }

            long famevalue = SectionFormular.getInvestFamevalue(citySection, value);

            long prosvalue = SectionFormular.getInvestProsperityvalue(value);

            CitySectionHelper.WriteLock();

            try
            {
                IEntityNoebeTransaction command = SettingHelper.EntityTransaction;
                command.Begin(delegate()
                {
                    if (UsrProfileDao.increaseFamevalue(profile, famevalue))
                    {
                        section.Scaletypecode = SysSectionScaleHelper.SearchByFamevalue(profile.Famevalue).Scaletypecode;

                        command.Update(section);
                    }

                    command.Update(profile);

                    command.Update(CitySectionHelper.unsafeIncreaseSectionProsperity(sectionserialcode, prosvalue));

                    command.Commit();
                });
            }
            finally
            {
                CitySectionHelper.WriteUnlock();
            }


            response.profile = UsrProfileFacade.ToProfile(profile);
            response.Succeed = true;
            return response;
        }

    }
    public interface section_invest : ISangoResponse
    {
        player_profile profile { get;set;}
    }
}
